function [prof_mean, prof_sem] = profavg(prof_data, col_cell);

% PROFAVG - average profiles
%
%    [MEAN, SEM] = PROFAVG(DATA, COLS) averages the columns specified
%    by the vectors within the cell array COLS.

% By:   S.C. Molitor (smolitor@med.unc.edu)
% Date: May 31, 2000

% initialize output

prof_mean = [];
prof_sem = [];

% validate arguments

if (nargin ~= 2)
   msgbox('Invalid number of arguments', 'PROFAVG Error', 'warn');
   return
elseif (~isnumeric(prof_data) | isempty(prof_data))
   msgbox('DATA must be a numeric array', 'PROFAVG Error', 'warn');
   return
elseif (~iscell(col_cell) | isempty(col_cell))
   msgbox('COLS must be a cell array', 'PROFAVG Error', 'warn');
   return
elseif (~all(cellfun('isreal', col_cell)) | any(cellfun('isempty', col_cell)))
   msgbox('All elements in COLS must be numeric arrays', 'PROFAVG Error', 'warn');
   return
end

% first column of output is first column of data

prof_mean = prof_data(:, 1);
prof_sem = prof_mean;

% average specified columns
% create SEM if more than one column

for i = 1 : length(col_cell)
   col_data = col_cell{i};
   if ((min(col_data) < 2) | (max(col_data) > size(prof_data, 2)))
      msgbox(sprintf('Invalid column range in average %d', i), 'PROFAVG Error', 'warn');
      return
   end
   prof_mean(:, i + 1) = mean(prof_data(:, col_data), 2);
   if (length(col_data) > 1)
      prof_sem(:, i + 1) = std(prof_data(:, col_data), 0, 2)/sqrt(length(col_data));
   else
      prof_sem(:, i + 1) = 0;
   end
end
return
